package com.house.system.service.impl;

import java.util.Date;
import java.util.List;

import com.house.common.annotation.DataScope;
import com.house.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.house.system.mapper.AppointmentMapper;
import com.house.system.domain.Appointment;
import com.house.system.service.IAppointmentService;

import javax.annotation.PostConstruct;

/**
 * 预约看房Service业务层处理
 *
 * @author tc
 * @date 2022-02-04
 */
@Service
public class AppointmentServiceImpl implements IAppointmentService {
    @Autowired
    private AppointmentMapper appointmentMapper;

    /**
     * 查询预约看房
     *
     * @param appointmentId 预约看房主键
     * @return 预约看房
     */
    @Override
    public Appointment selectAppointmentByAppointmentId(Long appointmentId) {
        return appointmentMapper.selectAppointmentByAppointmentId(appointmentId);
    }

    /**
     * 查询预约看房列表
     *
     * @param appointment 预约看房
     * @return 预约看房
     */
    @Override
    @DataScope(tableAlias = "a")
    public List<Appointment> selectAppointmentList(Appointment appointment) {
        return appointmentMapper.selectAppointmentList(appointment);
    }

    /**
     * 新增预约看房
     *
     * @param appointment 预约看房
     * @return 结果
     */
    @Override
    public int insertAppointment(Appointment appointment) {
        appointment.setCreateTime(DateUtils.getNowDate());
        return appointmentMapper.insertAppointment(appointment);
    }

    /**
     * 修改预约看房
     *
     * @param appointment 预约看房
     * @return 结果
     */
    @Override
    public int updateAppointment(Appointment appointment) {
        appointment.setUpdateTime(DateUtils.getNowDate());
        return appointmentMapper.updateAppointment(appointment);
    }

    /**
     * 批量删除预约看房
     *
     * @param appointmentIds 需要删除的预约看房主键
     * @return 结果
     */
    @Override
    public int deleteAppointmentByAppointmentIds(Long[] appointmentIds) {
        return appointmentMapper.deleteAppointmentByAppointmentIds(appointmentIds);
    }

    /**
     * 删除预约看房信息
     *
     * @param appointmentId 预约看房主键
     * @return 结果
     */
    @Override
    public int deleteAppointmentByAppointmentId(Long appointmentId) {
        return appointmentMapper.deleteAppointmentByAppointmentId(appointmentId);
    }

    /**
     * 每次启动都检查预约时间是否超时
     */
    @PostConstruct
    public void updateAppointmentStatus() {
        List<Appointment> appointments = appointmentMapper.selectAppointmentList(new Appointment());
        for (Appointment appointment : appointments) {
            Date appTime = appointment.getAppTime();
            Date nowDate = DateUtils.getNowDate();
            if (appTime.getTime() < nowDate.getTime() && "1".equals(appointment.getIsHandle())) {
                //如果中介已处理且预约时间超时,则预约失效
                appointment.setIsHandle("2");
                updateAppointment(appointment);
            }
        }
    }
}
